package cn.edu.ustc.multicore.exercise.ch2;

import java.util.concurrent.RecursiveTask;

public class PrefixSumInitTreeTask extends RecursiveTask<BtNode> {
	private int[] input;
	private int low, high;
	int sum;
	int fromleft;

	public PrefixSumInitTreeTask(int[] input, int low, int high) {
		this.input = input;
		this.low = low;
		this.high = high;
	}

	@Override
	protected BtNode compute() {
		if (low >= high)
			return null;
		else {
			if ((high - low) == 1) {
				BtNode leave = new BtNode(low, high);
				leave.setSum(input[low]);
				return leave;
			} else {
				int mid = (low + high) / 2;
				PrefixSumInitTreeTask left = new PrefixSumInitTreeTask(input, low, mid);
				PrefixSumInitTreeTask right = new PrefixSumInitTreeTask(input, mid, high);
				left.fork();
				right.fork();
				BtNode lchild = left.join();
				BtNode rchild = right.join();
				BtNode btn = new BtNode(low,high);
				if(rchild != null){
					btn.setSum(lchild.getSum() + rchild.getSum());
					btn.setLchild(lchild);
					btn.setRchild(rchild);
				}else{
					btn.setSum(lchild.getSum());
					btn.setLchild(lchild);
					btn.setRchild(null);
				}
				return btn;
			}
		}
	}

}
